#include "main.h"
#include <iostream>
#include <regex>
#define URL "https://wallhaven.cc/toplist?q=anime"

std::vector<std::string> Html_Search(std::string Content,std::string pattern_str,int &Img_Count,bool Add_Https);
std::string Find_ImgUrl(std::string Home_Url);

int main(int argc,char **argv){
	char* Root_Path = NULL;
	if(argc!=1){
		Root_Path = (char*)malloc(sizeof(char)*strlen(argv[1]));
		strcpy(Root_Path,argv[1]);
	}else{
		std::cout << FAILED << "没有输入存储路径,格式位 ./splider 路径" << std::endl;
		return -1;
	}
	std::string html_content = Get_Source(URL);
	std::cout << html_content << std::endl;
	std::string File_Path = "";
	int Img_Count = 0;
	//<a class="preview" href="https://alpha.wallhaven.cc/wallpaper/757424"  target="_blank"  >
	int i = 0;
	for(auto Home_Url:Html_Search(html_content,"<a class=\"preview\" href=\"(.+?)\"  target=\"_blank\"  >",Img_Count,false)){
			std::cout << SUCCESS << "找到图片主页:" << Home_Url << std::endl;
			std::string RealImg_Url = Find_ImgUrl(Home_Url);
			if(Img_Count!=0){
				std::string Picture_name = Html_Search(RealImg_Url,".*/(.+?\\.\\w{3,4})",i,false)[0];
				std::cout << "----->图片真实地址:" << RealImg_Url << std::endl;
				File_Path = Root_Path + Picture_name;
				std::cout << "------------>图片本地存储路径:" << File_Path << std::endl;
				Download(RealImg_Url.c_str(),File_Path.c_str());
			}
			else
				std::cout << FAILED << "Nothing Find" << std::endl;
	}
	std::cout << Img_Count << std::endl;

}

std::vector<std::string> Html_Search(std::string Content,const std::string pattern_str,int &Img_Count,bool Add_Https){
	std::vector<std::string> Result = {};
	std::smatch matcher;
	std::regex pattern(pattern_str);
	std::string Img_Url = "";
	while(std::regex_search(Content,matcher,pattern)){
		Content = matcher.suffix();
		Img_Url = (Add_Https ? "https:" : "")+matcher[1].str();
		Result.push_back(Img_Url);
		Img_Count++;
	}
	return Result;
}

std::string Find_ImgUrl(std::string Home_Url){
	int count = 0;
	std::string Source = Get_Source(Home_Url.c_str());
	std::vector<std::string> Matchers = {};
	Matchers = Html_Search(Source,"<img id=\"wallpaper\" src=\"(.+?)\"",count,false);
	if(Matchers.empty())
		return "";
	else
		return Matchers[0];
}
